from playwright._impl._api_types import TimeoutError
import pyautogui, pandas, ini_op, os, pdf_sortAndRename, calendar, duckdb, requests, json
from time import strftime

def run(llq, dwbh, parentId):
    start_date, end_date, start_pz_no, end_pz_no, pdf_folder = ini_op.getinivalue('pdf_config', 'start_date', 'end_date', 'start_pz_no', 'end_pz_no', 'pdf_folder')
    url_header, queryprintfsbzdj, queryprintfsbzdj_data = ini_op.getinivalue('request_config', 'url_header', 'queryprintfsbzdj', 'queryprintfsbzdj_data')
    pdf_folder = os.path.join(pdf_folder, parentId)
    os.makedirs(pdf_folder, exist_ok=True)
    pzh=''
    if start_pz_no != '':
        pzh = ',"FSBZDJ_PZH":"'+start_pz_no+'"'
    if end_pz_no != '':
        pzh = pzh + ',"FSBZDJ_ZZPZH":"'+end_pz_no+'"'
    queryprintfsbzdj_data = queryprintfsbzdj_data.replace('#start_date#', start_date)
    queryprintfsbzdj_data = queryprintfsbzdj_data.replace('#end_date#', end_date)
    queryprintfsbzdj_data = queryprintfsbzdj_data.replace('#pzh#', pzh)
    browser, context, page, header = llq
    page.click('#toolbar_header_function')
    page.fill('#search', '联合打印')
    try:
        page.wait_for_selector('ul.search--result-list', timeout=2000)
    except Exception:
        page.click('.header--search')
    page.locator('ul.search--result-list li').first.click()

    page.wait_for_selector('li.borderactive[title="联合打印"]')
    id = page.query_selector('.borderactive a').get_attribute('id')
    page.wait_for_selector("iframe#rtf_iframe_" + id[:-5])
    frame = page.query_selector("iframe#rtf_iframe_" + id[:-5]).content_frame()
    frame.wait_for_selector('#FSBZDJ_PZH')
    frame.fill('input#FSBZDJ_DWNM', dwbh)
    frame.locator('input#FSBZDJ_DWNM').press('Enter')
    frame.hover('#FSBZDJ_FSSC')
    frame.locator('#FSBZDJ_FSSC').locator('../../div').locator('.lee-clear').click()
    try:
        frame.wait_for_selector('#FSBZDJ_PZRQ_1', timeout=500)
    except TimeoutError:
        frame.click('.lee-filter-setting')
        frame.click('[for="lee-transfer-FSBZDJ_PZRQ"]')
        frame.click('.lee-transbtn-a')
        frame.click('.lee-dialog-btn-ok')
    
    global is_download, pzrq_now, pzh_now
    is_download = True
    conn = duckdb.connect('data.db')
    def download(pzrq, pzh, djbh):
        global is_download, pzrq_now, pzh_now
        frame.fill('#FSBZDJ_DJBH', djbh)
        # frame.click('#FSBZDJ_PZRQ_1')

        # frame.locator('span[lay-type="year"]').first.click()
        # frame.locator('li[lay-ym="'+pzrq[:4]+'"]').first.click()
        # frame.locator('span[lay-type="month"]').first.click()
        # frame.locator('li[lay-ym="'+str(int(pzrq[5:7])-1)+'"]').first.click()
        # frame.locator('td[lay-ymd="'+pzrq[:5]+str(int(pzrq[5:7]))+'-1"]').first.click()
        
        # frame.locator('span[lay-type="year"]').last.click()
        # frame.locator('li[lay-ym="'+pzrq[:4]+'"]').last.click()
        # frame.locator('span[lay-type="month"]').last.click()
        # frame.locator('li[lay-ym="'+str(int(pzrq[5:7])-1)+'"]').last.click()
        # frame.locator('td[lay-ymd="'+pzrq[:5]+str(int(pzrq[5:7]))+'-'+str(calendar.monthrange(int(pzrq[:4]), int(pzrq[5:7]))[1])+'"]').last.click()

        # frame.locator('.laydate-btns-confirm').click()
        frame.click('.lee-solution-search button:text-matches("筛选")')
        for i in range(3):
            try:
                frame.wait_for_selector('.lee-grid-pager-title span:text-matches("1")', timeout=5000)
                break
            except TimeoutError:
                frame.click('.lee-solution-search button:text-matches("筛选")')
        frame.wait_for_selector('td[id$=FSBZDJ_PZH] a[title="'+pzh+'"]', timeout=60000)

        while True:
            if is_download:
                break
            page.wait_for_timeout(1000)

        pzrq_now = pzrq
        pzh_now = pzh
        frame.locator('td[id$=FSBZDJ_PZH] a[title="'+pzh+'"]').locator('../../../td[substring(@id, string-length(@id) - string-length("FSBZDJ_PZRQ") + 1) = "FSBZDJ_PZRQ"]').locator('div[title="'+pzrq+'"]').click()
        frame.click('#toolbar1 span:text-matches("打印")')
        while True:
            try:
                frame.wait_for_selector('.lee-message-top-center .lee-alert span:text-matches("请选中一条单据")', timeout=1000)
                frame.locator('td[id$=FSBZDJ_PZH] a[title="'+pzh+'"]').locator('../../../td[substring(@id, string-length(@id) - string-length("FSBZDJ_PZRQ") + 1) = "FSBZDJ_PZRQ"]').locator('div[title="'+pzrq+'"]').click(timeout=1000)
                frame.click('#toolbar1 span:text-matches("打印")', timeout=1000)
                page.wait_for_timeout(1000)
            except TimeoutError:
                break

        while True:
            if not is_download:
                break
            page.wait_for_timeout(1000)
        page.click('li.borderactive[title="联合打印"] a[id^=BILLPRINT] .nav-link-close')
    
    def handle_response(response):
        global is_download, pzrq_now, pzh_now
        if "http://cpfms.casccloud.cn/api/BP/EIS/v1.0/imagedownload/print" in response.url and 'isBrowser' not in response.url:
            is_download = False
            print(response.url)
            pdf_page = context.new_page()
            pdf_page.goto(response.url)
            pdf_page.wait_for_timeout(2000)
            with pdf_page.expect_download(timeout=6000000) as download_info:
                pyautogui.hotkey('ctrl', 's')
            download = download_info.value
            filename = pzrq_now[:8]+pzh_now+'.pdf'
            filepath = os.path.join(pdf_folder, filename)
            download.save_as(filepath)
            conn.execute("insert into t_pdf_download (parentId, fileName, filepath) values (?, ?, ?)", [parentId, filename, filepath])
            pdf_page.close()
            is_download = True

    page.on('response', handle_response)

    url = url_header+queryprintfsbzdj
    result = requests.post(url, headers=header, json=json.loads(queryprintfsbzdj_data), verify=False)
    rows = result.json()['value']
    #保存为本地json文件
    # pandas.DataFrame(rows).to_json('data.json', orient='records', force_ascii=False)
    if len(rows) == 0:
        return
    for row in rows:
        download(row['FSBZDJ_PZRQ'], row['FSBZDJ_PZH'], row['FSBZDJ_DJBH'])
    while True:
        if is_download:
            break
        page.wait_for_timeout(1000)

    pdf_sortAndRename.run(parentId, pdf_folder)




    